<template>
  <el-card>
    <div class="mb-16">
      <el-button @click="router.back()">返回</el-button>
    </div>
    <el-timeline>
      <el-timeline-item v-for="item in historyList" :key="item.id" :timestamp="parseTime(item.deployTime)">
        <el-card style="width: calc(100% - 16px);">
          <p>{{ item.projectName }}-{{ item.title }}</p>
          <p>版本：{{ item.version }}</p>
          <p>备份文件：{{ item.backupFilePath }}</p>
          <div class="jend">
            <el-button v-if="item.backupFilePath" type="primary" :icon="RefreshLeft" circle :loading="rollBackLoading"
              @click="rollBack(item)" />
            <el-button type="danger" :icon="Delete" circle @click="handleDelete(item)" />
          </div>
        </el-card>
      </el-timeline-item>
    </el-timeline>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Delete, RefreshLeft } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import { deployRecordsStore, projectsStore, serversStore } from '@/utils/IndexDBWarp'
import { parseTime } from '@/utils/time'
import { confirmDialog, tips, tipsError } from '@/utils/tips'
import { invoke } from '@tauri-apps/api/core'
import { listen } from '@tauri-apps/api/event'
import { basename } from '@tauri-apps/api/path'
import { useLoadingBtn } from '@/hooks/useLoadingBtn'

const route = useRoute()
const router = useRouter()
const historyList = ref([])

onMounted(() => {
  getList()
})

const getList = () => {
  deployRecordsStore.serchList({ projectId: route.query.projectId }).then(res => {
    // 按时间倒序排序
    res.sort((a, b) => b.deployTime - a.deployTime)
    historyList.value = res
  })
}

const [rollBack, rollBackLoading] = useLoadingBtn(async (row) => {
  await confirmDialog(`确定回滚到 ${row.version} 吗？`)
  const info = await projectsStore.getById(row.projectId)
  const serverConfig = await serversStore.getById(info.serve)
  const zipName = await basename(row.backupFilePath)
  console.log('row', row)
  console.log('info', info)
  console.log('serverConfig', serverConfig)
  console.log('zipName', zipName)
  const afterScript = `
      cd ${info.remotePath}
      tar -xzvf ${zipName} --strip-components 1
  `

  // 监听事件回调
  const unlisten = await listen(row.id, (event) => {
    const { status, p, data } = event.payload
    console.log(status, p, data)
  });
  await invoke('upload_file', {
    eventId: row.id,
    host: `${serverConfig.host}:${serverConfig.port}`,
    username: serverConfig.username,
    password: serverConfig.password,
    localPath: row.backupFilePath,
    remotePath: `${info.remotePath}/${zipName}`,
    beforeScript: '',
    afterScript,
  }).catch(err => {
    console.log('err', err)
    tipsError(err)
    return Promise.reject(err)
  }).finally(() => {
    unlisten()
  })
  tips('回滚成功')
})

const handleDelete = async (row) => {
  await confirmDialog('确定删除吗？')
  await deployRecordsStore.deleteById(row.id)
  tips('删除成功')
  getList()
}
</script>

<style scoped lang="scss"></style>